<?php

namespace app\admin\model;

use think\Cache;
use think\Config;
use think\Model;

class Wxproduct extends Model
{
    // 表名
    protected $name = 'wxproduct';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'type_text',
        'unit_text',
        'wxproids_text',
    ];

    public function getTypeList()
    {
        $data = Config::get('wxproduct');
        if(!isset($data['type']))
        {
            return [];
        }
        return array_column(json_decode($data['type'],true),'name','id');
    }

    public function getWxproidsList()
    {
        $list = Cache::remember('wxProIds',function(){
            $pro = new Wxpro();
            return array_column(collection($pro->field('id,name,type,fenlei,kemu,banben')->select())->toArray(),'name','id');
        });
        return $list;
    }

    public function getUnitList()
    {
        return ['1' => __('Unit 1'),'2' => __('Unit 2')];
    }

    public function getTypeTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['type'];
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getWxproidsTextAttr($value, $data)
    {
        $value = $value ? $value : $data['wxpro_ids'];
        $list = $this->getWxproidsList();
        $arr = explode(',',$value);
        array_walk($arr,function (&$item) use ($list){
            if($item) $item = isset($list[$item]) ? $list[$item] : '';
        });
        return implode(',', $arr);
    }

    public function getUnitTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['unit'];
        $list = $this->getUnitList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 修改config的函数
     * @param $arr1 配置前缀
     * @param $arr2 数据变量
     * @return bool 返回状态
     */
    public function setConfig($arr,$file)
    {
        if (is_array($arr)) {
            $filename = $file . EXT;

            $filepath = APP_PATH . 'extra/' . $filename;
            if (!file_exists($filepath)) {
                $conf = "<?php return [];";
                file_put_contents($filepath, $conf);
            }

            $conf = include $filepath;
            foreach ($arr as $key => $value) {
                $conf[$key] = $value;
            }

            $time = date('Y/m/d H:i:s');
            $str = "<?php\r\n/**\r\n * 由extraconfig建立.\r\n * $time\r\n */\r\nreturn [\r\n";
            foreach ($conf as $key => $value) {
                $str .= "\t'$key' => '$value',";
                $str .= "\r\n";
            }
            $str .= '];';

            file_put_contents($filepath, $str);

            return true;
        } else {
            return false;
        }
    }


}
